#include <android_utils.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/system_properties.h>
#include "jni.h"
#include "md5.h"
#include "AESUtils.h"
#include "RSAUtils.h"
#include "common.h"

#define JNIREG_CLASS "com/security/encrypt/EncryptUtils"

size_t IS_REPEAT = 0;
/**
 * 记录主线程id
 */
pid_t MAIN_THREAD_ID;

JavaVM *mVm = NULL;

// JAVA本地接口方法表
static const JNINativeMethod METHODS[] = {

        {"dbb", "(Ljava/lang/String;[BLjava/lang/String;Ljava/lang/String;[B)Ljava/lang/String;",
         (void *) decryptByBytes},
        {"d", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[B)Ljava/lang/String;",
         (void *) decrypt},
        {"etb", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[B)[B",
         (void *) encryptToBytes},
        {"e", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[B)Ljava/lang/String;",
         (void *) encrypt},
        {"re", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", (void *) rsaEncrypt}
#ifdef DEBUG
        ,
        {"test", "(Ljava/lang/String;)[B", (void *) test}
#endif
};

/*
* Register several native methods for one class.
*/

static int registerNativeMethods(JNIEnv *env, const char *className,
                                 JNINativeMethod *gMethods, int numMethods) {
    jclass clazz;
    clazz = (*env)->FindClass(env, className);
    if (clazz == NULL) {
        return JNI_FALSE;
    }
    if ((*env)->RegisterNatives(env, clazz, gMethods, numMethods) < 0) {
        return JNI_FALSE;
    }

    LOGI("注册成功");

    return JNI_TRUE;
}

static int registerNatives(JNIEnv *env) {
    if (!registerNativeMethods(env, JNIREG_CLASS, (JNINativeMethod *) (METHODS),
                               sizeof(METHODS) / sizeof(METHODS[0])))
        return JNI_FALSE;

    return JNI_TRUE;
}

jint JNI_OnLoad(JavaVM *vm, void *reserved) {
    JNIEnv *env = NULL;
    jint result = -1;
    if (NULL != vm) {
        mVm = vm;
    } else {
        return result;
    }

    if ((*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_4) != JNI_OK) {
        return -1;
    }
//    assert(env != NULL);

    if (!registerNatives(env)) {//注册
        return -1;
    }

/* success -- return valid version number */

    result = JNI_VERSION_1_4;

    return result;
}